package com.simplenix.nicasio.admin.featsecurity;

import com.simplenix.nicasio.admin.eb.Group;
import com.simplenix.nicasio.admin.eb.User;
import com.simplenix.nicasio.admin.eb.UsuGroup;
import com.simplenix.nicasio.def.Feature;
import com.simplenix.nicasio.def.Module;
import com.simplenix.nicasio.hmaint.util.HMaintUtil;
import com.simplenix.nicasio.mb.Session;
import com.simplenix.nicasio.misc.Internationalization;
import com.simplenix.nicasio.misc.StrUtil;
import com.simplenix.nicasio.persistence.HibernateUtil;
import com.simplenix.nicasio.sys.FeatureSecurity;
import com.simplenix.nicasio.sys.SystemDef;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import org.hibernate.Transaction;

/**
 *
 * @author fronald
 */
public class AdminSecurity implements FeatureSecurity {

	public static final String LAST_URL = "LAST_URL";

	public void doSecurity(PageContext context, Module module, Feature feature) {
		Transaction t = HibernateUtil.getCurrentSession().getTransaction();
		if (!t.isActive()) {
			t.begin();
		}
		try {
			HttpServletResponse response = (HttpServletResponse) context.getResponse();
			HttpServletRequest request = (HttpServletRequest) context.getRequest();
			User u = (User) context.getSession().getAttribute(Session.CURRENT_USER);
			if (u == null) {
				String lastUri = ((HttpServletRequest) context.getRequest()).getRequestURI().replaceAll("\\.jsp", ".htm");
				if (!lastUri.equals(SystemDef.getInstance().getContextPath() + "/admin/misc/login.htm") && (lastUri.endsWith(".htm") || lastUri.endsWith(".jsp") || !lastUri.contains("."))) {
					context.getSession().setAttribute(LAST_URL, lastUri);
				}
				response.sendRedirect(SystemDef.getInstance().getContextPath() + "/admin/misc/login.htm");
			} else {
				String lastUri = StrUtil.nvl((String) context.getSession().getAttribute(LAST_URL));
				if (((feature.getName().equals("portal") && module.getName().equals("nicasio")) || u.getLogin().equals("admin")) && StrUtil.nvl(lastUri).equals("")) {
					return;
				}
				u = (User) HMaintUtil.findById(User.class, Long.toString(u.getUsuId()));
				if (!lastUri.equals("")) {
					context.getSession().removeAttribute(LAST_URL);
					response.sendRedirect(lastUri);
				} else {
					List<UsuGroup> usuGroups = u.getUsuGroups();
					boolean rtn = false;
					for (UsuGroup ug : usuGroups) {
						Group group = ug.getGroup();
						if (Group.haveAccess(group, module, feature)) {
							rtn = true;
							break;
						}
					}
					if (!rtn) {
						request.getSession().setAttribute(Session.FLASH_MESSAGE, Internationalization.getInstance().getString("access.denied"));
					}
				}
			}
		} catch (Exception ex) {
			Logger.getLogger(AdminSecurity.class.getName()).log(Level.SEVERE, null, ex);
		} finally {
			t.commit();
		}
	}

	public boolean haveAccess(HttpServletRequest request, Module module, Feature feature) {
		try {
			Transaction t = HibernateUtil.getCurrentSession().getTransaction();
			if (!t.isActive()) {
				t.begin();
			}
			User user = (User) request.getSession().getAttribute(Session.CURRENT_USER);
			if (user == null) {
				t.commit();
				return false;
			} else if (StrUtil.nvl(user.getLogin()).equals("admin")) {
				t.commit();
				return true;
			} else {
				user = (User) HMaintUtil.findById(User.class, Long.toString(user.getUsuId()));
				boolean rtn = false;
				for (UsuGroup g : user.getUsuGroups()) {
					if (rtn) {
						break;
					}
					Group group = g.getGroup();
					rtn = Group.haveAccess(group, module, feature);
				}
				t.commit();
				return rtn;
			}
		} catch (Exception e) {
			throw new NullPointerException(e.getLocalizedMessage());
		}
	}

}
